//
//  LSAnalyzeViewController.m
//  LookScore
//
//  Created by wr on 2018/3/20.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#define RATIO_WIDTH    LSAutoVlaue(77, LSScreenWidth)

#import "LSAnalyzeViewController.h"
#import "UIViewController+ZJScrollPageController.h"
#import "ZJScrollPageView.h"
#import "CustomSegmentedView.h"
#import "LSAnalyzeCell.h"
#import "LSArrowsView.h"
#import "LSCompetitionModel.h"
#import "LSAnalysisModel.h"
#import "LSMarchDetailModel.h"
@interface LSAnalyzeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(strong,nonatomic)UITableView *tableView;

@property(strong,nonatomic)NSMutableArray *modelArray;

@property(strong,nonatomic)NSArray *titlesArray;

@property(assign,nonatomic)NSInteger cellStyleFlag; //cell样式标识符

@property(strong,nonatomic)UIView *chooseView;

@property(strong,nonatomic)LSArrowsView *arrowsView;

@property(strong,nonatomic)NSMutableArray *controlArray;

@property (nonatomic, strong)NSMutableArray * matchModelArray;
@property (nonatomic, assign) NSInteger i ;

@property (nonatomic, strong) NSMutableArray * hostArray;

@end

@implementation LSAnalyzeViewController

- (NSMutableArray *)recordArray{
    if (!_hostArray) {
        _hostArray = @[].mutableCopy;
    }
    return _hostArray;
}

-(NSMutableArray *)controlArray{
    
    if (!_controlArray) {
        _controlArray=[NSMutableArray array];
        
    }
    return _controlArray;
}
- (NSMutableArray *)matchModelArray{
    if (!_matchModelArray) {
        _matchModelArray = @[].mutableCopy;
    }
    return _matchModelArray;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, LSScreenWidth, 300) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor =LSBackGroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
-(NSMutableArray *)modelArray{
    if(!_modelArray){
        _modelArray=[[NSMutableArray alloc]init];
    }
    return _modelArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _i = 5;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.cellStyleFlag = 0;
    
    self.titlesArray=@[@"历史战绩",@"近期战绩",@"积分排名",@"数据对比"];
    self.tableView.tableHeaderView=[self tableHeadView];
    [self.view addSubview:self.tableView];
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.sd_layout
    .leftEqualToView(self.view)
    .topEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view);
    
    [self loadAnalyzeData];
    LSRefreshHeaderView *header = [LSRefreshHeaderView headerWithRefreshingBlock:^{
        [self loadAnalyzeData];
    }];
    self.tableView.mj_header = header;// 设置header

}



- (void)loadAnalyzeData{
    [self.modelArray removeAllObjects];
    
    MyLog(@"-----%ld",self.matchId);
    NSDictionary *parameter = @{@"matchId":@(self.matchId),@"leagueId":@(self.leagueId),@"homeId":@(self.homeId),@"guestId":@(self.guestId)};//写死，后期传

    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    
    hud.mode=MBProgressHUDModeIndeterminate;
    
    
    [LSHttpEnclosureTool GET:LSDATABASEANALYSIS parameters:parameter resBlock:^(id responseObject) {
        if (responseObject) {
            LSAnalysisModel * model = [LSAnalysisModel mj_objectWithKeyValues:responseObject];
            [self.modelArray addObject:model];
            MyLog(@"AnalyzeData --- %@",responseObject);
            [self arrangementData:responseObject[@"MatchTeamRecordList"]];
        }
        [self.tableView.mj_header endRefreshing];
        [hud showAnimated:YES];
        [self.tableView reloadData];
    }];
}


- (void)arrangementData:(NSArray *)array{
    [self.matchModelArray removeAllObjects];
    [self.hostArray removeAllObjects];
    for (NSInteger i = 0; i<array.count; i++) {
        NSMutableArray * historyArray = @[].mutableCopy;
        NSMutableArray * hostArray = @[].mutableCopy;
        NSMutableArray * guestArray = @[].mutableCopy;
        NSMutableDictionary * dict = [array[i] mutableCopy];
        NSMutableArray * dataArray = dict[@"AnalysisHistoricalArrayList"];
        for (NSInteger j = 0; j<dataArray.count; j++) {
            NSDictionary * dict1 = dataArray[j];
            if ([dict1[@"DataType"] integerValue] == 0) {
                [historyArray addObject:dict1];
            }
            if ([dict1[@"DataType"] integerValue] == 1) {
                [hostArray addObject:dict1];
                
            }
            if ([dict1[@"DataType"] integerValue] == 2) {
                [guestArray addObject:dict1];
                
            }
            
        }
        

        self.hostArray = [[NSMutableArray alloc] initWithArray:@[hostArray,guestArray]];
        //判断数组的个数是否小于5 不小于则显示5个 小于 则 全部显示
        if (hostArray.count > 5) {
            hostArray = [hostArray subarrayWithRange:NSMakeRange(0, _i)].mutableCopy;
        }
        
        if (guestArray.count > 5) {
            guestArray = [guestArray subarrayWithRange:NSMakeRange(0, _i)].mutableCopy;
        }
        
        NSMutableDictionary * jinqiDict = @{}.mutableCopy;
        [jinqiDict setObject:hostArray forKey:@"teamArray"];
        [jinqiDict setObject:@(5) forKey:@"i"];
        NSMutableArray * array = @[].mutableCopy;
        [array addObject:jinqiDict];
        
        NSMutableDictionary * jinqiDict1 = @{}.mutableCopy;
        [jinqiDict1 setObject:guestArray forKey:@"teamArray"];
        [jinqiDict1 setObject:@(5) forKey:@"i"];
        [array addObject:jinqiDict1];
        [dict setObject:array forKey:@"recentRecord"];
        [dict setObject:historyArray forKey:@"AnalysisHistoricalArrayList"];
        [self.matchModelArray addObject:[MatchTeamRecordList mj_objectWithKeyValues:dict]];
        MyLog(@"%@",dict);
    }
    
   
    
}

#pragma mark 🔥 tableViewDelegate tableViewDataSource
-(UIView *)tableHeadView{
    
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, LSScreenWidth, 44)];
    backView.backgroundColor=LSTitleWhiteColor;
    
    
    CustomSegmentedView *aCustomSegmentedView=[[CustomSegmentedView alloc]initWidthCustomSegmentedViewFrame:CGRectMake(LSScareValue(100, LSScreenWidth)/2, 10, LSScreenWidth-LSScareValue(100, LSScreenWidth), 24) titlesArray:self.titlesArray seletedTitleColor:[UIColor whiteColor] normalTitleColor:LSSubColorFF9E44 seletedBgColor:LSSubColorFF9E44 normalBgColor:[UIColor whiteColor] bordeColor:LSSubColorFF9E44  borderWidth:1 seletedCustomViewIndex:^(NSInteger index) {
        
        self.cellStyleFlag = index;
        
        MyLog(@"选择第%zd板块",self.cellStyleFlag);
        [self.controlArray removeAllObjects];
        [self.tableView reloadData];
    }];
    [aCustomSegmentedView selectedDefaultSegmentedIndex:0];
    [backView addSubview:aCustomSegmentedView];
    
    
    
    return backView;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.cellStyleFlag == 0 ) {
        return self.matchModelArray.count;
    }else if ( self.cellStyleFlag == 1){
        
        return self.matchModelArray.count;
    }else{
        
       return self.modelArray.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.cellStyleFlag == 0 ) {
        MatchTeamRecordList * model1 = self.matchModelArray[section];
        return model1.AnalysisHistoricalArrayList.count;
    }else if ( self.cellStyleFlag == 1){
        MatchTeamRecordList * model1 = self.matchModelArray[section];
        return model1.recentRecord.count;
    }else if (self.cellStyleFlag == 2){
        LSAnalysisModel * model =  self.modelArray[section];
        return model.IntegralRankList.count;
    }else if (self.cellStyleFlag == 3){
        LSAnalysisModel * model =  self.modelArray[section];
        return model.AnalysisDataComparisonList.count;
    }else{
        
        return 6;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.cellStyleFlag == 1) {
        MatchTeamRecordList * model = self.matchModelArray[indexPath.section];
        recentRecord * model1 = model.recentRecord[indexPath.row];
        CGFloat height = [tableView cellHeightForIndexPath:indexPath model:model1 keyPath:@"model" cellClass:[LSAnalyzeRecentCell class] contentViewWidth:[tableView cellContentViewWith]];
        return height;
    }
    else if (self.cellStyleFlag == 4){
        return 60;
    }
    else {
        return 30;
    }
}



- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.cellStyleFlag == 0) {
        LSAnalyzeCell *cell=[LSAnalyzeCell AnalyzeCellByTableView:tableView];
        if (indexPath.row % 2 == 0) {
            cell.backgroundColor = LSSubGrayColorf7;
        }
        else{
            cell.backgroundColor = [UIColor whiteColor];
        }
//        LSAnalysisModel * aModel = self.modelArray[indexPath.section];
//        MatchTeamRecordList * model = aModel.MatchTeamRecordList[indexPath.row];
        MatchTeamRecordList * model = self.matchModelArray[indexPath.section];
        cell.model = model.AnalysisHistoricalArrayList[indexPath.row];
        return cell;
    }
    else if (self.cellStyleFlag == 1) {
        LSAnalyzeRecentCell *cell=[LSAnalyzeRecentCell AnalyzeRecentCellByTableView:tableView];

        MatchTeamRecordList * model = self.matchModelArray[indexPath.section];
        cell.marModel = self.marModel;
        cell.matchModel = model;
        cell.myIndexPath = indexPath;
        recentRecord * model1 =  model.recentRecord[indexPath.row];
        cell.model  = model1;
        cell.block = ^(NSString *str) {
            NSMutableArray * array = self.hostArray[indexPath.row];
            if (model1.i+5 < array.count) {
                _i = model1.i + 5;
                array =  [array subarrayWithRange:NSMakeRange(0, _i)].mutableCopy;
                NSDictionary * dict = @{@"teamArray":array,@"i":@(_i)};
                
                recentRecord * rmodel = [recentRecord mj_objectWithKeyValues:dict];
                model1.i = rmodel.i;
                model1.isSeeMoreHidden = NO;
                model1.teamArray = rmodel.teamArray.mutableCopy;
                MyLog(@"%ld",model1.i);
            }else{
                _i = array.count;
                
                NSDictionary * dict = @{@"teamArray":array,@"i":@(_i)};
                recentRecord * rmodel = [recentRecord mj_objectWithKeyValues:dict];
                model1.i = rmodel.i;
                model1.isSeeMoreHidden = YES;
                model1.teamArray = rmodel.teamArray;
            }
            
            
//            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [tableView reloadData];
        };
        return cell;
    }
    else if (self.cellStyleFlag == 2) {
        LSAnalyzeRankCell *cell=[LSAnalyzeRankCell AnalyzeRankCellByTableView:tableView];
        if (indexPath.row % 2 != 0) {
            cell.backgroundColor = LSSubGrayColorf7;
        }
        else{
            cell.backgroundColor = [UIColor whiteColor];
        }
        LSAnalysisModel * aModel = self.modelArray[indexPath.section];
        IntegralRankList * model = aModel.IntegralRankList[indexPath.row];
        cell.model = model;
        return cell;
    }
    else if (self.cellStyleFlag == 3) {
        LSAnalyzeDataCell *cell=[LSAnalyzeDataCell AnalyzeDataCellByTableView:tableView];
        if (indexPath.row % 2 != 0) {
            cell.backgroundColor = LSSubGrayColorf7;
        }
        else{
            cell.backgroundColor = [UIColor whiteColor];
        }
        LSAnalysisModel * aModel = self.modelArray[indexPath.section];
        AnalysisDataComparisonList * model = aModel.AnalysisDataComparisonList[indexPath.row];
        cell.model = model;
        return cell;
    }
    else if (self.cellStyleFlag == 4) {
        LSAnalyzeRecommendCell *cell=[LSAnalyzeRecommendCell AnalyzeRecommendCellByTableView:tableView];
        if (indexPath.row % 2 == 0) {
            cell.backgroundColor = LSSubGrayColorf7;
        }
        else{
            cell.backgroundColor = [UIColor whiteColor];
        }
        return cell;
    }else{
        
      return [UITableViewCell new];
    }
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (self.cellStyleFlag == 0) {
        return 150;
    }
    else if (self.cellStyleFlag == 2 || self.cellStyleFlag == 3){
        return 30;
    }else{
        return 0;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *header = [tableView headerViewForSection:section];
    if (!header) {
        header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, 44)];
        header.backgroundColor = [UIColor whiteColor];
    }
    
    if (self.cellStyleFlag == 0) {
        MatchTeamRecordList * model = self.matchModelArray[section];
        if (model.AnalysisHistoricalArrayList.count == 0) {
            UILabel  * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, header.frame.size.height-15)];
            label.text = @"暂无数据";
            label.font = LSFontSize17;
            label.textColor = LSTitleGrayColor1;
            [header addSubview:label];
            label.sd_layout
            .centerXEqualToView(header)
            .centerYEqualToView(header)
            .autoHeightRatio(0);
            [label setSingleLineAutoResizeWithMaxWidth:180];
            
            
        }else{
            [self.controlArray removeAllObjects];
            for (int i=0; i<3; i++) {
                
                //ratio
                UILabel *ratioLabel=[[UILabel alloc]init];
                ratioLabel.font=LSFontSize13;
                ratioLabel.textColor=LSTitleGrayColor3;
                ratioLabel.textAlignment=NSTextAlignmentCenter;
                [header addSubview:ratioLabel];
                
                [self.controlArray addObject:ratioLabel];
                
                UILabel *barChartLabel=[[UILabel alloc]init];
                barChartLabel.font=LSFontSize13;
                barChartLabel.textColor=LSTitleGrayColor3;
                [header addSubview:barChartLabel];
                [self.controlArray addObject:barChartLabel];
                
                UILabel *barChartBottomLabel=[[UILabel alloc]init];
                barChartBottomLabel.font=LSFontSize13;
                barChartBottomLabel.textColor=LSTitleGrayColor3;
                [header addSubview:barChartBottomLabel];
                [self.controlArray addObject:barChartBottomLabel];
                
                
                UILabel *gameTypeLabel=[[UILabel alloc]init];
                gameTypeLabel.font=LSFontSize13;
                gameTypeLabel.textColor=[UIColor blackColor];
                gameTypeLabel.textAlignment=NSTextAlignmentCenter;
                [header addSubview:gameTypeLabel];
                
                [self.controlArray addObject:gameTypeLabel];
                
                ratioLabel.sd_layout.leftEqualToView(header).offset((LSScreenWidth-RATIO_WIDTH*3)/2+RATIO_WIDTH*i).topSpaceToView(header, 22).widthIs(RATIO_WIDTH-20).heightIs(15);
                
                gameTypeLabel.sd_layout.leftEqualToView(header).offset((LSScreenWidth-RATIO_WIDTH*3)/2+RATIO_WIDTH*i).widthIs(RATIO_WIDTH-20).heightIs(15).bottomEqualToView(header).offset(-20);
                barChartBottomLabel.sd_layout.leftEqualToView(header).offset((LSScreenWidth-RATIO_WIDTH*3)/2+RATIO_WIDTH*i).widthIs(RATIO_WIDTH-20).heightIs(2).bottomSpaceToView(gameTypeLabel,13);
                
                barChartLabel.sd_layout.leftEqualToView(header).offset((LSScreenWidth-RATIO_WIDTH*3)/2+RATIO_WIDTH*i).widthIs(RATIO_WIDTH-20).heightIs(15).bottomSpaceToView(barChartBottomLabel, 0);
                
                
                
            }
           [self addfalseData:section];
        }
        
       
        
        return header;
    }
    else if (self.cellStyleFlag == 1){
        return header;
    }
    else if (self.cellStyleFlag == 2){
        header.backgroundColor = LSSubGrayColorf7;
        LSAnalysisModel * aModel = self.modelArray[section];
        
        if (aModel.IntegralRankList.count == 0) {
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, header.frame.size.height-15)];
            label.text = @"暂无数据";
            label.textAlignment = NSTextAlignmentCenter;
            [header addSubview:label];
        }else{
            NSArray *titleArray = @[@"排名",@"球队",@"已赛",@"胜/平/负",@"得/失",@"净胜球",@"积分"];
            CGFloat width=(LSScreenWidth - 20)/7;
            UILabel *lable;
            for (int i=0; i<7; i++) {
                lable=[UILabel new];
                lable.text = titleArray[i];
                lable.textColor = LSTitleGrayColor3;
                lable.font = LSFontSize(12, LSScreenWidth);
                lable.textAlignment = NSTextAlignmentCenter;
                lable.tag=i;
                [header addSubview:lable];
                lable.sd_layout.leftEqualToView(self.view).offset(width*i + 10).topEqualToView(self.view).centerYEqualToView(self.view).widthIs(width).heightIs(30);
        }
        
            
        }
        return header;
    }
    else if (self.cellStyleFlag == 3){
        header.backgroundColor = LSSubGrayColorf7;
        LSAnalysisModel * aModel = self.modelArray[section];
        if (aModel.AnalysisDataComparisonList.count == 0) {
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, header.frame.size.height-15)];
            label.text = @"暂无数据";
            label.textAlignment = NSTextAlignmentCenter;
            [header addSubview:label];
        }else{
            NSArray *titleArray = @[@"球队",@"总进球",@"均进",@"总失",@"均失",@"胜率",@"平均",@"负率"];
            CGFloat width=(LSScreenWidth - 20)/8;
            UILabel *lable;
            for (int i=0; i<titleArray.count; i++) {
                lable=[UILabel new];
                lable.text = titleArray[i];
                lable.textColor = LSTitleGrayColor3;
                lable.font = LSFontSize(12, LSScreenWidth);
                lable.textAlignment = NSTextAlignmentCenter;
                lable.tag = i;
                [header addSubview:lable];
                lable.sd_layout.leftEqualToView(self.view).offset(width*i + 10).topEqualToView(self.view).centerYEqualToView(self.view).widthIs(width).heightIs(30);
                
            }
        }
        
        return header;
    }
    else{
        return header;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}


-(void)addfalseData:(NSInteger)section{
    MatchTeamRecordList * model = self.matchModelArray[section];
    NSMutableArray * winArray = @[].mutableCopy;
    NSMutableArray * flatArray = @[].mutableCopy;
    NSMutableArray * lossArray = @[].mutableCopy;
    for (AnalysisHistoricalArrayList * model1 in model.AnalysisHistoricalArrayList) {
        
        if ([model1.QOutcome isEqualToString:@"胜"]) {
            [winArray addObject:model1];
        }else if ([model1.QOutcome isEqualToString:@"平"]){
            [flatArray addObject:model1];
            
        }else if ([model1.QOutcome isEqualToString:@"负"]){
            
            [lossArray addObject:model1];
        }
    }
    
    [self.controlArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UILabel *label=(UILabel *)obj;
        if (idx==0) {
            label.text= [NSString stringWithFormat:@"%ld",winArray.count];
            label.textColor=Color(224, 100, 88);
        }else if (idx==1){
            label.backgroundColor=Color(236, 169, 164);
            
            float h = 60 * winArray.count / model.AnalysisHistoricalArrayList.count;
            //            label.backgroundColor=LSSubColorf25e59;
            label.sd_layout.heightIs(h);
        }else if (idx==2){
            label.backgroundColor=Color(224, 100, 88);
            //            label.backgroundColor=LSSubColorDF1C1C;
        }else if (idx==3){
            label.text=@"主胜";
            label.textColor=[UIColor blackColor];
        }else if (idx==4){
            label.text= [NSString stringWithFormat:@"%ld",flatArray.count];
            label.textColor=Color(100, 172, 217);
            
        }else if (idx==5){
            label.backgroundColor=Color(174, 211, 234);
            //              label.backgroundColor=LSSubColor75b8fe;
            float h = 60 * flatArray.count / model.AnalysisHistoricalArrayList.count;
            label.sd_layout.heightIs(h);
            
        }else if (idx==6){
            label.backgroundColor=Color(100, 172, 217);
            //             label.backgroundColor=LSSubColor5cd2df;
            
        }else if (idx==7){
            label.text=@"平局";
            label.textColor=[UIColor blackColor];
        }else if (idx==8){
            label.text= [NSString stringWithFormat:@"%ld",lossArray.count];
            label.textColor=Color(70, 144, 101);
            
        }else if (idx==9){
            label.backgroundColor=Color(154, 195, 172);
            //            label.backgroundColor=LSSubColor9dd3cc;
            float h = 60 * lossArray.count / model.AnalysisHistoricalArrayList.count;
            label.sd_layout.heightIs(h);
        }else if (idx==10){
            label.backgroundColor=Color(70, 144, 101);
            //            label.backgroundColor=LSNavMainColor;
        }else if (idx==11){
            label.text=@"客胜";
            label.textColor=[UIColor blackColor];
        }
//        [self.contentView layoutIfNeeded];
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


